﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Uniforax.Core.Common;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace Uniforax.Core.GameActions.GridMove
{
    public class GridLeaveAction : BaseGridMoveAction
    {
        // 起点的目标。
        public PosId FromPosId { get; set; }

        public override void Execute(ActionContext context)
        {
            var world = context.GameWorld;

            var grid = world.GetGrid(FromPosId);

            var objectId = ObjectId;

            // 设定上，游戏单位会在此处。
            var gameObject = grid.GetPlacedObject(objectId);
            if (gameObject is null)
            {
                throw new NullReferenceException($"GridLeaveAction.Execute: 无法在 {grid} 找到 Id 为 {objectId} 的对象。");
            }

            // leave
            var leaveContext = new GameObjectLeaveGridMovementContext()
            {
                GameObject = gameObject,
                OldGrid = grid,
            };

            grid.RemovePlacedObject(gameObject);
            world.RestoreTempGameObject(gameObject, objectId); // 将 grid 的 游戏对象放到 world 的临时存储区。 
            grid.OnGameObjectLeave(context, leaveContext);
        }

        public override void Undo(ActionContext context)
        {
            var world = context.GameWorld;

            var grid = world.GetGrid(FromPosId);
            var objectId = ObjectId;
            var gameObject = world.GetRestoredTempGameObject(objectId);
            grid.PlaceObject(gameObject);
            world.RemoveRestoredTempGameObject(gameObject);
        }
    }
}
